//
//  ScanUI.m
//  mbstore
//
//  Created by huangyi on 14-3-12.
//  Copyright (c) 2014年 huangyi. All rights reserved.
//

#import "ScanUI.h"
#import <AVFoundation/AVFoundation.h>
#import "MBProgressHUD.h"

@interface ScanUI () <AVCaptureMetadataOutputObjectsDelegate>{
    AVCaptureSession *_session;
    AVCaptureDevice *_device;
    AVCaptureDeviceInput *_input;
    AVCaptureMetadataOutput *_output;
    AVCaptureVideoPreviewLayer *_prevLayer;

    UIView *_highlightView;
    UILabel *_label;
}

@end

@implementation ScanUI

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.

    self.title=@"扫一扫";

    UIButton *cancel=[UIButton buttonWithType:UIButtonTypeCustom];
    [cancel setTitle:@"取消" forState:UIControlStateNormal];
    [cancel sizeToFit];
    [cancel addTarget:self action:@selector(onCancelClick:) forControlEvents:UIControlEventTouchUpInside];
    self.navigationItem.leftBarButtonItems=@[cancel.barButtonItem];

    _highlightView = [[UIView alloc] init];
    _highlightView.autoresizingMask = UIViewAutoresizingFlexibleTopMargin|UIViewAutoresizingFlexibleLeftMargin|UIViewAutoresizingFlexibleRightMargin|UIViewAutoresizingFlexibleBottomMargin;
    _highlightView.layer.borderColor = [UIColor greenColor].CGColor;
    _highlightView.layer.borderWidth = 3;
    [self.view addSubview:_highlightView];

    _label = [[UILabel alloc] init];
    _label.frame = CGRectMake(0, self.view.bounds.size.height - 40, self.view.bounds.size.width, 40);
    _label.autoresizingMask = UIViewAutoresizingFlexibleTopMargin;
    _label.backgroundColor = [UIColor colorWithWhite:0.15 alpha:0.65];
    _label.textColor = [UIColor whiteColor];
    _label.textAlignment = NSTextAlignmentCenter;
    _label.text = @"(---)";
    [self.view addSubview:_label];

    _session = [[AVCaptureSession alloc] init];
    _device = [AVCaptureDevice defaultDeviceWithMediaType:AVMediaTypeVideo];
    NSError *error = nil;

    _input = [AVCaptureDeviceInput deviceInputWithDevice:_device error:&error];
    if (_input) {
        [_session addInput:_input];
    } else {
        NSLog(@"Error: %@", error);
    }

    _output = [[AVCaptureMetadataOutput alloc] init];
    
    [_session addOutput:_output];
    [_output setMetadataObjectTypes:@[AVMetadataObjectTypeUPCECode, AVMetadataObjectTypeCode39Code, AVMetadataObjectTypeCode39Mod43Code, AVMetadataObjectTypeEAN13Code, AVMetadataObjectTypeEAN8Code, AVMetadataObjectTypeCode93Code, AVMetadataObjectTypeCode128Code,AVMetadataObjectTypePDF417Code, AVMetadataObjectTypeQRCode, AVMetadataObjectTypeAztecCode]];
    [_output setMetadataObjectsDelegate:self queue:dispatch_get_main_queue()];
//    _output.metadataObjectTypes = [_output availableMetadataObjectTypes];

    _prevLayer = [AVCaptureVideoPreviewLayer layerWithSession:_session];
    _prevLayer.frame = self.view.bounds;
    if ([[_prevLayer connection] isVideoOrientationSupported]) {
        [[_prevLayer connection] setVideoOrientation:AVCaptureVideoOrientationPortrait];
    }

    _prevLayer.videoGravity = AVLayerVideoGravityResizeAspectFill;
    [self.view.layer addSublayer:_prevLayer];

    [_session startRunning];

    [self.view bringSubviewToFront:_highlightView];
    [self.view bringSubviewToFront:_label];


    self.cameraImageView.image=[UIImage imageNamed:@"media.bundle/crosshair.png"];
    [self.view bringSubviewToFront:self.cameraImageView];
    [self.view bringSubviewToFront:self.cameraTextLabel];

}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

-(void)onCancelClick:(id)sender{
    [self.navigationController popViewControllerAnimated:YES];
}

- (void)captureOutput:(AVCaptureOutput *)captureOutput didOutputMetadataObjects:(NSArray *)metadataObjects fromConnection:(AVCaptureConnection *)connection
{
    CGRect highlightViewRect = CGRectZero;
    AVMetadataMachineReadableCodeObject *barCodeObject;
    NSString *detectionString = nil;
    NSArray *barCodeTypes = @[AVMetadataObjectTypeUPCECode, AVMetadataObjectTypeCode39Code, AVMetadataObjectTypeCode39Mod43Code,
                              AVMetadataObjectTypeEAN13Code, AVMetadataObjectTypeEAN8Code, AVMetadataObjectTypeCode93Code, AVMetadataObjectTypeCode128Code,
                              AVMetadataObjectTypePDF417Code, AVMetadataObjectTypeQRCode, AVMetadataObjectTypeAztecCode];

    for (AVMetadataObject *metadata in metadataObjects) {
        for (NSString *type in barCodeTypes) {
            if ([metadata.type isEqualToString:type])
            {
                barCodeObject = (AVMetadataMachineReadableCodeObject *)[_prevLayer transformedMetadataObjectForMetadataObject:(AVMetadataMachineReadableCodeObject *)metadata];
                highlightViewRect = barCodeObject.bounds;
                detectionString = [(AVMetadataMachineReadableCodeObject *)metadata stringValue];
                break;
            }
        }
        [_session stopRunning];
        [MBProgressHUD showHUDAddedTo:self.view animated:YES];
        if (detectionString != nil)
        {
            _label.text = detectionString;
            dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
                HTTPClient *client=[AppUI getProduct:detectionString];
                if (!client.error) {
                    NSDictionary *response=[client.responseData JSONObject];
                    dispatch_async(dispatch_get_main_queue(), ^{
                        [MBProgressHUD hideAllHUDsForView:self.view animated:YES];
                        NSArray *details=[response valueForKey:@"DetailEntitys"];
                        if (![details isEqual:[NSNull null]]&&details.count>0) {
                            NSDictionary *detail=[details firstObject];
                            if (detail) {
                                NSString *prodID = [detail objectForKey:@"ProdID"];
                                
                                [self foundMatch:prodID];
                            }
                        }else{
                            NSString * erromsg = [response valueForKey:@"ErrMessage"];
                            UIAlertView *alert=[[UIAlertView alloc] initWithTitle:@"提示" message:erromsg delegate:self cancelButtonTitle:@"继续扫描" otherButtonTitles:@"看一看", nil];
                            [alert show];
                        }
                        
                    });
                }
            });
            
            break;
        }
        else{
            _label.text = @"(---)";
        }
    }

    _highlightView.frame = highlightViewRect;
}

#warning TODO: 扫码
-(void)foundMatch:(NSString*)scan{
    
    if (_label.tag==100) {//利用label的tag来控制扫描是否激活
        return;
    }else{
        _label.tag=100;
    }
      #warning 调用数据库
    NSArray *items=[AppUI getSuitByScan:scan];//本地检索图片
    if (items.count>0) {
        MainApp *app=[MainApp mainApp];
        [app.itemList removeAllObjects];
        [app.itemList addObjectsFromArray:items];
        [[NSNotificationCenter defaultCenter] postNotificationName:ItemListNotification object:self];
    }else{
        NSString *text=@"很抱歉，未找到您要的商品，特为您推荐最新上架商品。";
        UIAlertView *alert=[[UIAlertView alloc] initWithTitle:text message:nil delegate:self cancelButtonTitle:@"继续扫描" otherButtonTitles:@"看一看", nil];
        [alert show];
    }
}

-(void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex{
    if (buttonIndex>0) {        
#warning 调用数据库
        NSArray *items=[AppUI getAllSuit];
        MainApp *app=[MainApp mainApp];
        [app.itemList removeAllObjects];
        [app.itemList addObjectsFromArray:items];
        [[NSNotificationCenter defaultCenter] postNotificationName:ItemListNotification object:self];
    }else{
        _label.tag=0;
        [_session startRunning];
    }
}
@end
